package edu.hawaii.duedates.webApp;

import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import edu.hawaii.duedates.configuration.DueDatesConfiguration;
import edu.hawaii.duedates.configuration.User;

/**
 * The java implementation of the Index page of the DueDates
 * application that creates a simple login page. Upon login, user
 * credentials are checked against user data in the DueDatesConfiguration
 * object.
 * 
 * @author Tyler Wolff, Mari-Lee Flestado, Aric West
 */
public class Index extends DueDatesPage {
  
  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /**
   * Constructs the Index page of the DueDates web application.
   */
  public Index () {
    
    // Add CSS definitions for this page
    add(HeaderContributor.forCss(
        edu.hawaii.duedates.webApp.Index.class, "style/login.css", "screen"));  
    
    Form form = new Form("loginForm");
    form.add(new TextField("LoginEmail", new PropertyModel(getSession(), "email")));
    form.add(new PasswordTextField("LoginPassword", new PropertyModel(getSession(), "password")));
    
    form.add(new Button("Login") {
      
      private static final long serialVersionUID = 1L;
    
      /** Validates email & password and goes to ResultPage */
      @Override
      public void onSubmit() {
        
        DueDatesConfiguration config = getDueDatesSession().getDueDatesConfiguration();
        User user = config.validateUser(getDueDatesSession().getEmail(), 
            getDueDatesSession().getPassword());
        
        // If user data exists in XML configuration file
        if (user == null) {
          //TODO clear the error message somewhere else?
          getDueDatesSession().setErrorMessage("Invalid login credentials. Please try again.");
          setResponsePage(Index.class);
        }
        else {
          getDueDatesSession().setUser(user);
          getDueDatesSession().setSmtpServer(config.getSmtpServer()); 
          String resultString = getDueDatesSession().getUser().getLibraryArgs();
          String[] resultArgs = resultString.split(" ");
          getDueDatesSession().setDueDatesObject(resultArgs);        
          setResponsePage(ResultPage.class); 
        }
        
      }
    });
    
   add(new Label("LoginError", getDueDatesSession().getErrorMessage()));
   add(form);
  } //end index
}
